import asyncio  
  
balance = 0  
lock = asyncio.Lock()

async def change_it_with_lock(n):  
    async with lock:  
        global balance  
        balance = balance + n  
        await asyncio.sleep(1)  
        balance = balance - n  
  
        print(balance)

# 最终状态一致，但过程中不一致
async def change_it_without_lock(n):  
  
    global balance  
  
    balance = balance + n  
    await asyncio.sleep(1)  
    balance = balance - n  
  
    print(balance)  
  
  
async def main():
    tasks = []
    for i in range(5):  # 创建5个协程1 2 3 4 5
        # task = asyncio.create_task(change_it_without_lock(i + 1))
        task = asyncio.create_task(change_it_with_lock(i + 1))
        tasks.append(task)
    
    await asyncio.gather(*tasks)  # 等待所有任务完成

    print(balance)

if __name__ == '__main__':
    asyncio.run(main())